package com.FrameWork.Synchoronization;

import java.util.Observable;
import java.util.Observer;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.method.ScrollingMovementMethod;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.FrameWork.Common.AbstractBaseActivity;
import com.FrameWork.Common.MyApplication;
import com.FrameWork.Entity.ProgressEntity;
import com.SFA.R;
import com.umeng.analytics.MobclickAgent;

public class SyncActivity extends AbstractBaseActivity
implements Observer,OnClickListener
{
	private boolean running = false;
	public static final int RESULT_SYNCCANCELED = -100;
	public static final int RESULT_SYNCSUCCESSFUL = 100;
	public ProgressBar	syncprogressbar;
	private com.FrameWork.Common.BorderTextView tvLog = null;
	private TextView tvLastTime = null;
	private TextView tvTimer = null;
	private Button btnSync;
	private Thread thread = null;
	private TextView tvStatus = null;
	private EditText txtPrintAddress;
	private Button btnPrintAddress;
	SharedPreferences preferencce;
	private OnClickListener click = new OnClickListener()
	{

		@Override
		public void onClick(View v) {
			syncprogressbar.setProgress(0);
			btnSync.setEnabled(false);
			tvLog.setText("");
			minute = second=Millisecond=0;
			handler.postDelayed(runnable,100); // 开始Timer
			thread = new Thread(null,dobackgroundSync,"Background");
			thread.start();

		}

	};  


	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.syncactivity);
		preferencce = this.getSharedPreferences("PRINT", Context.MODE_PRIVATE);
		txtPrintAddress = (EditText) findViewById(R.id.txtPrintAddress);
		btnPrintAddress = (Button) findViewById(R.id.btnPrintAddress);
		btnPrintAddress.setOnClickListener(this);
		txtPrintAddress.setText(preferencce.getString("ADDRESS", "http://192.168.1.3/"));
		tvLog = (com.FrameWork.Common.BorderTextView) findViewById(R.id.tvLog);
		tvLog.setEnabled(false);
		tvStatus= (TextView) findViewById(R.id.tvStatus);
		tvLastTime= (TextView) findViewById(R.id.tvLastTime);
		tvTimer= (TextView) findViewById(R.id.tvTimer);
		btnSync= (Button) findViewById(R.id.btnSync);
		btnSync.setOnClickListener(click);
		syncprogressbar = (ProgressBar) findViewById(R.id.syncProgressBar);
		syncprogressbar.setMax(100);
		ShowLastTime();
		ShowSyncModel();
		if(MyApplication.getInstance().SyncMonitor != null)
			MyApplication.getInstance().SyncMonitor.Observer = this;
		//判断当前的同步模式，如果为非初始化模式而且有数据的情况下，则提示用户是否进行数据
		//上传同步
		try
		{
			if(SynchConfig.Instance(SyncActivity.this).getSyncModel() != SyncModel.InitialSync)
			{
				int count = new SynchLogicManager().GetUnuploadDataCount(MyApplication.getInstance().SyncMonitor.Process);
				if(count>0)
				{
					new AlertDialog.Builder(context).setTitle("有" + count + "未上传数据，你希望马上上传吗?").
					setIcon(android.R.drawable.ic_dialog_info).setPositiveButton("上传",
							new DialogInterface.OnClickListener()
					{
						@Override
						public void onClick(DialogInterface dialog,
								int which)
						{
							click.onClick(btnSync);
						}

					}).setNegativeButton("取消", null).show();  
				}
			}
		}
		catch(Exception err)
		{
			err.printStackTrace();
		}
	}

	private void ShowSyncModel()
	{
		String value="1";
		SynchConfig config =SynchConfig.Instance(SyncActivity.this);
		if(config.getSyncModel() == SyncModel.InitialSync)
		{
			value ="0";

		}
		else
		{
			value = config.getSyncModel()== SyncModel.InitialSync ? "0" : "1";
		}
		try
		{
			tvStatus.setText("当前同步方式:" + this.getResources().getStringArray(R.array.STRING_SYNCH_MODEL)[Integer.parseInt(value)]);
		}
		catch(Exception err)
		{

		}
	}


	private void ShowLastTime()
	{
		//Display the Last Synchronization Time;
		long LastTime= SynchConfig.Instance(SyncActivity.this).LastSyncTime;
		if(LastTime==0)
			tvLastTime.setText(R.string.NEVER_SYNC);
		else
		{
			String temp = "";
			String strDate = String.valueOf(LastTime);
			if(strDate.length()>=14)
			{
				temp= strDate.substring(0, 4);
				temp +="年";
				temp+= strDate.substring(4,6);
				temp+="月";
				temp +=strDate.substring(6,8);
				temp+="日";
				temp +=strDate.substring(8,10);
				temp+=":";
				temp +=strDate.substring(10,12);
			}
			tvLastTime.setText(temp);

		}
	}

	@Override
	public void update(Observable observable, Object data) {
		// TODO Auto-generated method stub
		Message message= new Message();
		Bundle b = new Bundle();
		b.putSerializable("ENTITY", (ProgressEntity)data);
		message.setData(b);
		handler.sendMessage(message);

	}


	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		this.ShowSyncModel();
	}

	protected void onDestroy ( ) {
		handler.removeCallbacks(runnable); //停止Timer 
		super.onDestroy( );
	}


	public final Handler handler = new Handler()
	{

		public void handleMessage(Message msg)
		{
			if(msg.what == 100)
			{
				ShowLastTime();
				btnSync.setEnabled(true);
				//				btnSetting.setEnabled(true);
				setProgressBarVisibility(false);
				return;
			}
			else if(msg.what == -1)
			{
				btnSync.setEnabled(true);
				//				btnSetting.setEnabled(true);
				setProgressBarVisibility(false);
			}
			else
			{
				ProgressEntity entity = (ProgressEntity)msg.getData().getSerializable("ENTITY");
				String data = entity.Message + "\r\n";
				if(data != null && tvLog != null)
				{


					tvLog.append(data);
					//tvLog.requestLayout();
					tvLog.setSelection(tvLog.getText().length() , tvLog.getText().length());
					tvLog.setMovementMethod(ScrollingMovementMethod.getInstance());
				}
				syncprogressbar.setProgress(entity.Increment);

			}



		}
	};

	private Runnable dobackgroundSync= new Runnable()
	{
		public void run() 
		{
			if(running)
				return;
			running = true;

			Synchronization synch = new Synchronization(SyncActivity.this);
			try {

				synch.SynchConfig = SynchConfig.Instance(SyncActivity.this);
				synch.addObserver(SyncActivity.this);
				boolean successful = synch.StartSynchronization(SyncActivity.this);
				if(SyncActivity.this.isFinishing())
				{
					return;
				}
				if(successful)
				{
					ProgressEntity entity = new ProgressEntity();
					entity.Increment=100;
					entity.Message = context.getResources().getString(R.string.SYNCH_SUCCESS);
					synch.notifyObservers(entity);
					Message msg = new Message();
					msg.what=100;
					handler.sendMessage(msg);
					if(getIntent() != null && getIntent().getAction() != null && getIntent().getAction().equals(Intent.ACTION_SYNC))
					{
						Activity activity = SyncActivity.this;
						Intent result = new Intent();
						activity.setResult(RESULT_SYNCSUCCESSFUL,result);
						activity.finish();
					}
				}
				else
				{
					ProgressEntity entity = new ProgressEntity();
					entity.Increment=100;
					entity.Message = context.getResources().getString(R.string.SYNCH_FAIL);

					synch.notifyObservers(entity);
					Message msg = new Message();
					msg.what=-1;
					handler.sendMessage(msg);
				}
			} 
			catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				MobclickAgent.reportError(SyncActivity.this, e.getMessage());
				Message msg = new Message();
				msg.what=-1;
				handler.sendMessage(msg);
			}
			finally
			{

				handler.removeCallbacks(runnable); //停止Timer 

			}
			synch.deleteObserver(SyncActivity.this);
			running = false;
		}
	};

	// 分钟
	public static int	 minute = 0;
	// 秒
	public static int	 second = 0;
	// 秒
	public static int	 Millisecond = 0;

	private Runnable runnable = new Runnable( ) 
	{
		@Override
		public void run()
		{
			Millisecond = Millisecond + 1;
			if (Millisecond == 10)
			{
				second = second + 1;
				Millisecond = 0;
			}
			if (second == 60)
			{
				minute = minute + 1;
				second = 0;
			}
			if (minute == 60)
			{
				minute = 0;
			}
			String text = "";

			if(minute<10)
				text ="0" + minute + ":";
			else
				text =minute + ":";
			if(second<10)
				text +="0" + second;
			else
				text +=second;
			text +="." + Millisecond;
			tvTimer.setText(text);
			handler.postDelayed(this,100); 

		}
	};

	@Override
	public void onClick(View arg0) {
		Editor editor = preferencce.edit();
		editor.putString("ADDRESS", txtPrintAddress.getText().toString());
		editor.commit();


		
	}



}